##

rm(list = ls())

library(tidyverse)
library(lfe)
library(stargazer)

source("code/helper_functions.R")

## Function to tidy a list of felm objects

tidy_felm_list <- function(model_list) {
    model_list %>%
        lapply(tidy_felm) %>%
        reduce(bind_rows)
}

## Load number of outlets

df <- read_rds("data/n_outlets_2009.rds")

glimpse(df)

## Main data set

btw <- readRDS("data/data_main.RDS") %>%
    dplyr::select(
        county_id_2018,
        year,
        matches("right_total_zweit"),
        -matches("diff"),
        turnout,
        east,
        state,
        treat_categorical4,
        matches("covar")
    ) %>%
    filter(!year == 2013) %>%
    filter(year == 2009)

## Municipal debt data

d <- read_delim("data/debt_counties.csv", delim = ";") %>%
    dplyr::select(1, 4) %>%
    dplyr::rename(county_id_2018 = 1, debt_total = 2) %>%
    filter(!is.na(county_id_2018)) %>%
    mutate(debt_total = str_remove_all(debt_total, "\\.")) %>%
    mutate(debt_total = str_replace_all(debt_total, "\\,", "\\.")) %>%
    mutate(debt_total = as.numeric(debt_total))


## Combine these

df <- df %>%
    left_join(d) %>%
    left_join(btw) %>%
    mutate(debt_total = debt_total)

## Debt is measured per capita

## Models

m1 <- felm(debt_total ~ n_outlets_now_unique | 0 | 0 | 0,
    data = df
)

m2 <- felm(
    debt_total ~ n_outlets_now_unique +
        covar_pop_total + covar_gdp_pc + covar_emp_rate +
        right_total_zweit | 0 | 0 | 0,
    data = df
)

m3 <- felm(
    debt_total ~ n_outlets_now_unique +
        covar_pop_total + covar_gdp_pc + covar_emp_rate +
        right_total_zweit | state | 0 | 0,
    data = df
)

m4 <- felm(debt_total ~ I(log(1 + n_outlets_now_unique)) | 0 | 0 | 0,
    data = df
)

m5 <- felm(
    debt_total ~ I(log(1 + n_outlets_now_unique)) +
        covar_pop_total + covar_gdp_pc + covar_emp_rate +
        right_total_zweit | 0 | 0 | 0,
    data = df
)

m6 <- felm(
    debt_total ~ I(log(1 + n_outlets_now_unique)) +
        covar_pop_total + covar_gdp_pc + covar_emp_rate +
        right_total_zweit | state | 0 | 0,
    data = df
)


## Check

out <- list(m1, m2, m3, m4, m5, m6) %>% 
  tidy_felm_list() %>% 
  filter(str_detect(term, "outlets"))

sd_list <- out$dv_sd
mean_list <- out$dv_mean

## Table A.9

stargazer(list(m1, m2, m3, m4, m5, m6),
    keep.stat = c("n", "rsq"),
    add.lines = list(
        c("Covariates", rep(c("No", "Yes", "Yes"), 2)),
        c("State FE", rep(c("No", "No", "Yes"), 2))
    ),
    keep = "outlets",
    covariate.labels = c(
        "Number of outlets",
        "Number of outlets (log)"
    ),
    style = "ajps",
    dep.var.caption = "Municipal debt per capita"
)


